﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using log4net;
using System.Deployment.Application;
using System.Reflection;

namespace Riel_Gestion
{
    public partial class FrmMain : Form
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(FrmMain));
        private long contSeg = 0;
        
        public string CurrentVersion
        {
            get
            {
                return ApplicationDeployment.IsNetworkDeployed
                       ? ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString()
                       : Assembly.GetExecutingAssembly().GetName().Version.ToString();
            }
        }
        
        public FrmMain()
        {
            log4net.Config.XmlConfigurator.Configure();            
            InitializeComponent();

            Change_BackgroundImage(LocalProperties.getInstance().getProperty("wallpapper"), LocalProperties.getInstance().getProperty("wpLayout"));
        }

        private void agregarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            logger.Info("Accediendo a FrmAgregarCliente...");
            FrmAgregarCliente frmAgregarCliente = new FrmAgregarCliente();
            frmAgregarCliente.ShowDialog();
        }
       
        private void acercaDeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            logger.Info("Accediendo a AcercaDe...");
            FrmAbout about = new FrmAbout();
            about.ShowDialog();
        }

        private void salirToolStripMenuItem_Click(object sender, EventArgs e)
        {
            logger.Info("Saliendo de la aplicación...");
            DialogResult dialogResult = MessageBox.Show("¿Desea salir de la aplicación?", this.Text, MessageBoxButtons.YesNo,MessageBoxIcon.Question,MessageBoxDefaultButton.Button2);
            if (dialogResult == DialogResult.Yes)
            {
                this.Close();
            }
        }

        private void fichaToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            logger.Info("Accediendo a FrmListadoProveedores...");
            FrmListadoProveedores frmListadoProveedores = new FrmListadoProveedores(this);
            frmListadoProveedores.MdiParent = this;
            frmListadoProveedores.Show();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            logger.Info("Accediendo a FrmAgregarCliente...");
            FrmAgregarCliente frmAgregarCliente = new FrmAgregarCliente();
            frmAgregarCliente.ShowDialog();
        }

        private void agregarToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            logger.Info("Accediendo a FrmAgregarProveedor...");
            FrmAgregarProveedor frmAgregarProveedor = new FrmAgregarProveedor();
            frmAgregarProveedor.ShowDialog();
        }

        private void cToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmPropiedades frmPropiedades = new FrmPropiedades();
            frmPropiedades.ShowDialog();

            Change_BackgroundImage(LocalProperties.getInstance().getProperty("wallpapper"), LocalProperties.getInstance().getProperty("wpLayout"));            
        }

        private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            logger.Info("======= Se Cierra Aplicacion =======");
            Application.Exit();
        }

        private void listadoDeClientesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            logger.Info("Accediendo a FrmListadoCliente...");
            FrmListadoCliente frmListadoCliente = new FrmListadoCliente(this);
            frmListadoCliente.MdiParent = this;
            frmListadoCliente.Show();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            logger.Info("Accediendo a FrmListadoCliente...");
            FrmListadoCliente frmListadoCliente = new FrmListadoCliente(this);
            frmListadoCliente.MdiParent = this;            
            frmListadoCliente.Show();
        }

        private void depuracionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            logger.Info("Accediendo a FrmFiltroDepuracion...");
            FrmFiltroDepuracion frmFiltroDepuracion = new FrmFiltroDepuracion();
            frmFiltroDepuracion.ShowDialog();
        }

        private void balanceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            logger.Info("Accediendo a FrmFiltroBalance...");
            FrmFiltroBalance frmFiltroBalance = new FrmFiltroBalance();
            frmFiltroBalance.ShowDialog();            
        }
       
        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            logger.Info("Accediendo a FrmAgregarProveedor...");
            FrmAgregarProveedor frmAgregarProveedor = new FrmAgregarProveedor();
            frmAgregarProveedor.ShowDialog();
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            logger.Info("Accediendo a FrmListadoProveedores...");
            FrmListadoProveedores frmListadoProveedores = new FrmListadoProveedores(this);
            frmListadoProveedores.MdiParent = this;
            frmListadoProveedores.Show();
        }

        private void importarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            logger.Info("Importando backup");
            string fileToCopy = Application.StartupPath + "\\" + "riel.mdb";
            ofd.FileName = "riel.bak";
            ofd.Filter = "Riel backup files (*.bak)|*.bak|All files (*.*)|*.*";
            
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    logger.Info("Importando backup: " + ofd.FileName);
                    System.IO.File.Copy(ofd.FileName, fileToCopy, true);
                    MessageBox.Show("Archivo Importado exitosamente!", "Importar", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    logger.Info("Archivo Importado exitosamente!");
                }
                catch (Exception ex)
                {
                    logger.Error(ex.Message, ex);
                    showErrorDialog(ex.Message);
                }
                
            }
        }

        private void exportarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string fileToCopy = Application.StartupPath + "\\" + "riel.mdb";
            sfd.FileName = "riel.bak";
            sfd.Filter = "All files (*.*)|*.*";
            sfd.FilterIndex = 1;
            sfd.RestoreDirectory = true;

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    logger.Info("Exportando backup a: " + sfd.FileName);
                    System.IO.File.Copy(fileToCopy, sfd.FileName, true);
                    MessageBox.Show("Archivo resguardado exitosamente!", "Exportar", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    logger.Info("Archivo Exportado exitosamente!");
                }
                catch (Exception ex)
                {
                    logger.Error(ex.Message, ex);
                    showErrorDialog(ex.Message);
                }
            }
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            logger.Info("Accediendo a FrmFiltroVendedores...");
            FrmFiltroVendedores frmFiltroVendedores = new FrmFiltroVendedores();
            frmFiltroVendedores.ShowDialog();
        }

        private void vendedoresToolStripMenuItem_Click(object sender, EventArgs e)
        {
            logger.Info("Accediendo a FrmFiltroVendedores...");
            FrmFiltroVendedores frmFiltroVendedores = new FrmFiltroVendedores();
            frmFiltroVendedores.ShowDialog();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            logger.Info("Accediendo a FrmFiltroBalance...");
            FrmFiltroBalance frmFiltroBalance = new FrmFiltroBalance();
            frmFiltroBalance.ShowDialog();
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            logger.Info("Accediendo a FrmVentasGenerales...");
            FrmVentasGenerales frmVentasGenerales = new FrmVentasGenerales();
            frmVentasGenerales.MdiParent = this;
            frmVentasGenerales.Show();
        }

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            logger.Info("Accediendo a FrmCompra...");
            FrmCompra frmCompra = new FrmCompra();
            frmCompra.MdiParent = this;
            frmCompra.Show();
        }

        private void timerFechaHora_Tick(object sender, EventArgs e)
        {
            contSeg++;
            DateTime dt = DateTime.Now;
            lblBarraStatusFechaHora.Text = String.Format("{0:F}", dt);

            if (contSeg == (3600 * int.Parse(LocalProperties.getInstance().getProperty("perBackAuto"))))
                generarBackup();
        }

        private void generarBackup()
        {
            string fileToCopy = Application.StartupPath + "\\" + "riel.mdb";
            string newFileName = Application.StartupPath + "\\localBackups\\" + "riel-" + String.Format("{0:yyyyMMdd_HHmmss }", DateTime.Now) + ".bak";
            try
            {
                logger.Info("Generando backup: " + newFileName);
                System.IO.File.Copy(fileToCopy, newFileName, true);
                logger.Info("Backup generado exitosamente!");
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);                
            }
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            logger.Info("=====================================");
            logger.Info("   INICIANDO RIEL GESTION V" + CurrentVersion);
            logger.Info("=====================================");
            timerFechaHora.Start();


            try
            {
            //    pictureBox.Image = Image.FromFile(LocalProperties.getInstance().getProperty("wallpapper"));
            //    pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;

            //    if ("Centrado".Equals(LocalProperties.getInstance().getProperty("wpLayout")))
            //        pictureBox.SizeMode = PictureBoxSizeMode.CenterImage;

            //    if ("Expandido".Equals(LocalProperties.getInstance().getProperty("wpLayout")))
            //        pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;

            }
            catch (Exception ex)
            {
                logger.Warn(ex.Message);
            }           
        }

        public static void showErrorDialog(String errMsg)
        {
            MessageBox.Show(errMsg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public static void showInfoDialog(String errMsg,String titulo)
        {
            MessageBox.Show(errMsg, titulo, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public static DialogResult showInfoYesNoDialog(String errMsg, String titulo)
        {
            return MessageBox.Show(errMsg, titulo,MessageBoxButtons.YesNo,MessageBoxIcon.Question);
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            logger.Info("Cerrando, consulto si desea realizar Back Up y exportarlo...");
            if (showInfoYesNoDialog("¿Desea generar un Back Up y exportarlo?", "Riel Gestion") == DialogResult.Yes)
                exportarToolStripMenuItem_Click(sender, e);

        }


        private void Change_BackgroundImage(string _path, string layout)
        {
            string imagepath = _path;
            System.IO.FileStream fs;
            // MDI Form image background layout change here
            //(Remember control imagebakground layout take default form background layount )
            if ("Centrado".Equals(layout))
                this.BackgroundImageLayout = ImageLayout.Center;
            if ("Mosaico".Equals(layout))
                this.BackgroundImageLayout = ImageLayout.Tile;
            if ("Expandido".Equals(layout))
                this.BackgroundImageLayout = ImageLayout.Stretch;
            
            // Checking File exists if yes go --->
            if (System.IO.File.Exists(imagepath))
            {
                // Read Image file
                fs = System.IO.File.OpenRead(imagepath);
                fs.Position = 0;
                // Change MDI From back ground picture
                foreach (Control ctl in this.Controls)
                {
                    if (ctl is MdiClient)
                    {
                        //ctl.BackColor = Color.AntiqueWhite;
                        ctl.BackgroundImage = System.Drawing.Image.FromStream(fs);
                        break;
                    }
                }
            }
            else
            {
                // Change MDI From back ground picture
                foreach (Control ctl in this.Controls)
                {
                    if (ctl is MdiClient)
                    {
                        //ctl.BackColor = Color.AntiqueWhite;
                        ctl.BackgroundImage = null;
                        break;
                    }
                }
            }
        }

    }
}
